package gw.com.android.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;
import com.tinkerpatch.sdk.TinkerPatch;

import java.io.File;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.presenter.AdsConfigPresenter;
import gw.com.android.presenter.AdverPagePresenter;
import gw.com.android.presenter.LaunchPagePresenter;
import gw.com.android.presenter.http.ConfigFileRequest;
import gw.com.android.ui.bulletin.NotifyRequest;
import gw.com.android.utils.ENV;
import gw.com.android.utils.ImageUtil;
import gw.com.android.utils.OpenApi;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ThreadPool;
import www.com.library.app.Logger;
import www.com.library.util.AESCrypto3;
import www.com.library.util.PermissionUtil;

public class WelcomeActivity extends BaseActivity {

    private static final int DELAY = 3000;

    @BindView(R.id.welacome_layout)
    RelativeLayout mlayout;
    @BindView(R.id.image_top)
    ImageView mImageView;

    private Runnable r;
    private AdvertiseCompletedListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setAcitivityParam() {
        /*
         * 我们需要判断:该意图是打开一个新的任务,还是将后台的应用给提到前台来.
         * 若是要将应用提到前台来直接将这个Activity结束掉,然后显示出来的Activity就是之前被最小化的Activity.
         * 因为点击图标的意图会将新启动的Activity置于顶端,而顶端的下面的Activity就是之前被最小化的Activity.
         * 此时结束掉新启动的Activity,就可以让之前被最小化的Activity 显示出来了
         */
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_welcome;
    }

    @Override
    protected void initLayoutView() {
        LaunchPagePresenter.Page page = LaunchPagePresenter.fetch();
        if (page != null) {
            File image = page.getImageFile();
            if (image.exists()) {
                /*if (image.getName().endsWith("gif") || image.getName().endsWith("GIF")) {
                    Glide.with(this).load(image).into(mImageView);
				} else {
					Bitmap bitmap = ImageUtil.getBitmapFromFile(image);
					mImageView.setImageBitmap(bitmap);
				}*/
                Glide.with(this).load(image).into(mImageView);
                return;
            }
        }
//		mlayout.setBackgroundResource(R.drawable.a_splash_screen_bg);
        Bitmap bitmap1 = ImageUtil.getBitmapFromResource(R.mipmap.a_splash);
        mImageView.setImageBitmap(bitmap1);
//		ImageUtil.scaleImage(this, mImageView, R.mipmap.a_splash);
    }

    @Override
    protected void initViewData() {
        final long start = System.currentTimeMillis();
        Logger.i("AdverPagePresenter", "welcome");
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                requestConfig();
                new NotifyRequest().getCategory(null);//取得所有的消息类型，并且注入到本地文件存储起来
                //指标数据库copy
                AppMain.getApp().initParam();
                AppMain.getApp().copyFormular();
                // 初始化 第三方库(极光推送样式)
                initJPush();
                GTConfig.instance().setJpushAliasAndTags(new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        System.out.println("welcomeActivity = " + s);
                        if (i == 0) {
                            OpenApi.pushDataByEvent(PackStatis.EventAction.START.getValue(), s);
                            try {
                                GTConfig.instance().alias = AESCrypto3.Encrypt(s);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }, "");
                long duration = System.currentTimeMillis() - start;
                onInitCompleted(duration);
            }
        });
        if (BuildConfig.TINKER_ENABLE) {
            TinkerPatch.with().fetchPatchUpdate(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(WelcomeActivity.this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    @Override
    protected void onDestroy() {
        PackStatis.ocpcActivate();
        if (r != null) {
            AppMain.getApp().getHandler().removeCallbacks(r);
            r = null;
        }
        super.onDestroy();
        if (listener != null) {
            AdverPagePresenter.getInstance().setOnCompletedListener(null);
            listener = null;
        }
        if (Util.isOnMainThread() && !this.isFinishing()) {
            Glide.with(this).pauseRequests();
        }
    }

    /**
     * 初始化极光推送
     */
    private void initJPush() {
        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(this, R.layout.dialog_notify_push, R.id.notify_icon, R.id.notify_text_apkname, R.id.notify_text);
        builder.layoutIconDrawable = ENV.getAppIcon(this);
        builder.developerArg0 = "developerArg2";
        JPushInterface.setPushNotificationBuilder(2, builder);
    }

    /**
     * 请求配置中心数据
     */
    private void requestConfig() {
        AdsConfigPresenter.getInstance().loadAds();
        ConfigFileRequest.getVersion();
    }

    /**
     * 启动页3秒后，并且初始化已经完成，才能进入MainActivity
     */
    private void onInitCompleted(long duration) {
        Logger.i("AdverPagePresenter", "init duration = " + duration);
        /*if (AppMain.getApp().isMonkeyRunning()) {
            return;
        }*/
        long delay = DELAY - duration;
        Logger.i("AdverPagePresenter", "init delay = " + delay);
        if (delay <= 0) delay = 0;
        if (!AdverPagePresenter.getInstance().needDownload() || AdverPagePresenter.getInstance().isCompleted()) {
            delay = 0;
        } else {
            listener = new AdvertiseCompletedListener();
            AdverPagePresenter.getInstance().setOnCompletedListener(listener);
        }
        r = new Runnable() {
            @Override
            public void run() {
                forward();
            }
        };
        AppMain.getApp().getHandler().postDelayed(r, delay);
    }

    private class AdvertiseCompletedListener implements AdverPagePresenter.OnCompletedListener {
        @Override
        public void onCompleted() {
            Logger.i("AdverPagePresenter", "load completed and show advertise now");
            if (r != null) {
                AppMain.getApp().getHandler().removeCallbacks(r);
            }
            forward();
        }
    }

    private void forward() {
        if (!GTConfig.instance().getBooleanValue(GTConfig.PREF_USER_HELP) && ConfigUtil.instance().hasUserGuideFunction()) {
            PackStatis.getToService(PackStatis.EventAction.START.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, "1");
            ActivityManager.showHelpActivity(WelcomeActivity.this, true, "", "");
        } else {
            if (showAdvertisePage()) {
                return;
            }
            if (getIntent().getExtras() != null && getIntent().getIntExtra("where", 0) == AppContances.TYPE_FORM_NOTIFY) {
                // 来自于推送
                PackStatis.getToService(PackStatis.EventAction.START.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, "2");
                ActivityManager.showMainTab(WelcomeActivity.this, ConfigType.TAB_HOME_TAG, getIntent().getExtras());
            } else {
                PackStatis.getToService(PackStatis.EventAction.START.getValue(), PackStatis.EventCategory.MAIN.getValue(), null, "1");
                ActivityManager.showMainTab(WelcomeActivity.this, ConfigType.TAB_HOME_TAG, 0);
            }
            WelcomeActivity.this.finish();
        }
    }

    private boolean showAdvertisePage() {
        boolean completed = AdverPagePresenter.getInstance().isCompleted();
        Logger.i("AdverPagePresenter", "showAdvertisePage completed = " + completed);
        if (completed) {
            Intent intent = new Intent();
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                intent.putExtras(extras);
            }
            intent.setClass(this, AdvertiseActivity.class);
            startActivity(intent);
            finish();
            overridePendingTransition(R.anim.fade_enter, R.anim.fade_out);
            return true;
        }
        return false;
    }

    @Override
    public void requestPermission(PermissionUtil.OnRequestPermissionResult result) {
        super.requestPermission(new PermissionUtil.OnRequestPermissionResult() {
            @Override
            public void onGranted() {
                requestContactPermission();
            }

            @Override
            public void onRefused() {
            }
        });
    }

    /**
     * 集团需求，访问通讯录，首次启动时弹出一次权限提示，用户如拒绝后，不再提示
     */
    private void requestContactPermission() {
        if (PermissionUtil.hasPermission(this, Manifest.permission.READ_CONTACTS)) {
            requestCallLogPermission();
        } else {
            boolean requested = GTConfig.instance().getBooleanValue("request_contacts_permission", false);
            if (requested) {
                requestCallLogPermission();
            } else {
                new PermissionUtil().requestPermission(this, Manifest.permission.READ_CONTACTS, AppContances.REQUEST_PERMISSION_ACCESS_CONTACT, null);
            }
        }
    }

    /**
     * 集团需求，访问通话记录，首次启动时弹出一次权限提示，用户如拒绝后，不再提示
     */
    private void requestCallLogPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN || PermissionUtil.hasPermission(this, Manifest.permission.READ_CALL_LOG)) {
            onPermissionGranted();
        } else {
            boolean requested = GTConfig.instance().getBooleanValue("request_call_log_permission", false);
            if (requested) {
                onPermissionGranted();
            } else {
                new PermissionUtil().requestPermission(this, Manifest.permission.READ_CALL_LOG, AppContances.REQUEST_PERMISSION_ACCESS_CALLLOG, null);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length <= 0) {
            return;
        }
        if (requestCode == AppContances.REQUEST_PERMISSION_ACCESS_CONTACT) {
            GTConfig.instance().setBooleanValue("request_contacts_permission", true);
            requestCallLogPermission();
        } else if (requestCode == AppContances.REQUEST_PERMISSION_ACCESS_CALLLOG) {
            GTConfig.instance().setBooleanValue("request_call_log_permission", true);
            onPermissionGranted();
        }
    }

}
